//
//  TSProgressSlider.swift
//  Pods
//
//  Created by 100Years on 2025/4/22.
//

import UIKit

open class TSProgressSlider: UISlider {
    // 透明覆盖视图
    private let overlayView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupOverlay()
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        setupOverlay()
    }
    
    private func setupOverlay() {
        semanticContentAttribute = .forceLeftToRight
//        if kIsRTL {
//            semanticContentAttribute = .forceRightToLeft
//        }
        
        // 配置透明覆盖视图
        overlayView.backgroundColor = .clear
        overlayView.isUserInteractionEnabled = true
        addSubview(overlayView)
        
        // 添加拖动手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        overlayView.addGestureRecognizer(panGesture)
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        overlayView.addGestureRecognizer(tapGesture)
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        // 确保覆盖视图与slider同大小
        overlayView.frame = bounds
    }
    
    // 处理拖动手势
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: overlayView)
        updateSliderValue(with: location)
        
        if gesture.state == .ended {
            sendActions(for: .touchUpInside)
        }
    }
    
    // 处理点击手势
    @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: overlayView)
        updateSliderValue(with: location)
        sendActions(for: .touchUpInside)
    }
    
    // 更新滑块值
    private func updateSliderValue(with location: CGPoint) {
        var percentage = max(0, min(1, location.x / bounds.width))
//        if kIsRTL {
//            percentage = 1.0 - percentage
//        }
        setValue(Float(percentage), animated: false)
        sendActions(for: .valueChanged)
    }
}
